//
//  MissionViewModel.swift
//  lightMaze
//
//  Created by aby on 2019/11/15.
//  Copyright © 2019 aby. All rights reserved.
//

import Foundation
import UIKit
import Combine

class MissionViewModel {
    let popResponder: NavigatePop
    init(pop: NavigatePop, size: Int = 4,lightSquene: [Int] = []) {
        self.popResponder = pop
        self.size = size
        lights = Array.init(repeating: Array.init(repeating: Light(), count: size), count: size)
        updateLightStatus(lightSequence: lightSquene)
    }
    
    
    @Published var timeString = "00:00"
    @Published var clickTimes = 0
    @Published var lights = [[Light]]()
    
    @Published var isWin = false
    
    private var currentStatus: GameStatus = .during {
        didSet {
            switch currentStatus {
            case .win:
                isWin = true
            case .lose:
                isWin = false
            default:
                break
            }
        }
    }
    
    var screenWith: CGFloat {
        return UIScreen.main.bounds.width
    }
    
    var screenHeight: CGFloat {
        return UIScreen.main.bounds.height
    }
    
    private(set) var size: Int = 4 // 游戏尺寸的大小，默认值为4
    private(set) var timer: Timer? // 计时器
    private var durations = 1 // 游戏持续的时间
    
    /// MARK: - Function
    func exit() {
        popResponder.pop()
    }
    
    func start(_ lightSqueue: [Int]) {
        currentStatus = .during
        clickTimes = 0
        timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true, block: { [weak self] (timer) in
            guard let `self` = self else { return }
            let min = self.durations >= 60 ? self.durations / 60 : 0
            let seconds = self.durations - min * 60
            let minString = min >= 10 ? "\(min)" : "0\(min)"
            let secondString = self.durations - min * 60 >= 10 ? "\(seconds)" : "0\(seconds)"
            self.timeString = minString + ":" + secondString
            self.durations += 1
        })
    }
    
    // 停止定时器
    func timerStop() {
        timer?.fireDate = Date.distantFuture
    }
    
    // 启动定时器
    func timerRestart() {
        durations = 0
        timeString = "00:00"
        timer?.fireDate = Date()
    }
    
    func circleWidth() -> CGFloat {
        let padding: CGFloat = 20
        let innerSpacing: CGFloat = 20
        var circleWidth = (screenWith - padding - (CGFloat(size) * innerSpacing)) / CGFloat(size)
        if circleWidth > screenWith / 5 {
            circleWidth = screenWith / 5.0
        }
        return circleWidth
    }
    
    /// 通过坐标索引修改灯状态
    /// - Parameters:
    ///   - column: 灯-列索引
    ///   - size: 灯-行索引
    func updateLightStatus(column: Int, row: Int) {
        lights[row][column].status.toggle()
        
        // 上
        let top = row - 1
        if !(top < 0) {
            lights[top][column].status.toggle()
        }
        // 下
        let bottom = row + 1
        if !(bottom > lights.count - 1) {
            lights[bottom][column].status.toggle()
        }
        // 左
        let left = column - 1
        if !(left < 0) {
            lights[row][left].status.toggle()
        }
        // 右
        let right = column + 1
        if !(right > lights.count - 1) {
            lights[row][right].status.toggle()
        }
        updateGameStatus()
    }
    
    private func updateGameStatus(){
        var lightingCount = 0
        for lightArr in lights {
            for light in lightArr {
                if light.status { lightingCount += 1 }
            }
        }
        
        if lightingCount == size * size - 1 {
            timerStop()
            currentStatus = .lose
            return
        }
        if lightingCount == 0 {
            timerStop()
            currentStatus = .win
            return
        }
    }
    
    private func updateLightStatus(lightSequence: [Int]) {
        for lightIndex in lightSequence {
            var index = lightIndex
            if index >= size * size {
                index = size * size - 1
            }
            let row = lightIndex / size
            let column = lightIndex % size
            updateLightStatus(column: column, row: row)
        }
    }
}

extension MissionViewModel {
    enum GameStatus {
        case win
        case lose
        case during
    }
}
